﻿namespace BathroomLocator.Phone.Pages
{
    using System;
    using System.Windows;
    using Microsoft.Phone.Controls;
    using Microsoft.Phone.Shell;

    public partial class ConnectPage : PhoneApplicationPage
    {
        private readonly ICloudClientFactory cloudClientFactory;

        public ConnectPage()
            : this(App.CloudClientFactory)
        {
        }

        public ConnectPage(ICloudClientFactory cloudClientFactory)
        {
            this.InitializeComponent();

            this.cloudClientFactory = cloudClientFactory;
            this.Loaded += this.ConnectPageLoaded;
        }

        private static T GetApplicationState<T>(string key)
        {
            if (!PhoneApplicationService.Current.State.ContainsKey(key))
            {
                return default(T);
            }

            return (T)PhoneApplicationService.Current.State[key];
        }

        private static void RemoveApplicationState(string key)
        {
            if (PhoneApplicationService.Current.State.ContainsKey(key))
            {
                PhoneApplicationService.Current.State.Remove(key);
            }
        }

        private void ConnectPageLoaded(object sender, RoutedEventArgs e)
        {
            var userWantsToGoBack = GetApplicationState<bool>("UserGoesBack");
            var userWantsToLogout = GetApplicationState<bool>("UserLogout");
            var userAlreadyLoggedIn = GetApplicationState<bool>("UserLoggedIn");

            if (userWantsToLogout)
            {
                this.Logout();
            }
            else if (userWantsToGoBack)
            {
                // Show an empty splash screen.
                this.Message.Text = string.Empty;
                this.Progress.Visibility = Visibility.Collapsed;
            }
            else if (userAlreadyLoggedIn)
            {
                // Navigate to the main pivot page and register the application
                // with the push notification service in case 'push notification'
                // is enabled by the user.
                this.NavigationService.Navigate(new Uri("/Pages/MainPage.xaml", UriKind.Relative));
            }
            else
            {
                this.Message.Text = "Signing in...";
                this.Progress.Visibility = Visibility.Visible;

                // If there is a valid authentication token available in the isolated storage,
                // then the application navigates to the main pivot page and is registered with 
                // the push notification service in case 'push notification' is enabled by the user.
                // If there is not any valid authentication token available in the isolated storage,
                // then the application navigates to the login page.
                this.cloudClientFactory.VerifyLoggedIn(
                    () => this.NavigationService.Navigate(new Uri("/Pages/MainPage.xaml", UriKind.Relative)),
                    () => this.NavigationService.Navigate(new Uri("/Pages/LoginPage.xaml", UriKind.Relative)));
            }
        }

        private void Logout()
        {
            //this.Message.Text = "Unregistering from Push Notification Service...";
            this.Progress.Visibility = Visibility.Visible;

            RemoveApplicationState("UserGoesBack");
            RemoveApplicationState("UserLogout");
            RemoveApplicationState("UserLoggedIn");

            // Clean the current authentication token.
            this.cloudClientFactory.CleanAuthenticationToken();

            // Navigate to the login page.
            this.NavigationService.Navigate(new Uri("/Pages/LoginPage.xaml", UriKind.Relative));

			//var pushNotificationClient = this.cloudClientFactory.ResolvePushNotificationClient();
			//pushNotificationClient.Disconnect(
			//    r =>
			//    {
			//        this.Dispatcher.BeginInvoke(
			//            () =>
			//            {
			//                this.Message.Text = string.Empty;

			//                if (r.Exception != null)
			//                {
			//                    MessageBox.Show(r.Exception.Message, "Push Unregistration Error", MessageBoxButton.OK);
			//                }

			//                // Clean the current authentication token.
			//                this.cloudClientFactory.CleanAuthenticationToken();

			//                // Navigate to the login page.
			//                this.NavigationService.Navigate(new Uri("/Pages/LoginPage.xaml", UriKind.Relative));
			//            });
			//    });
        }
    }
}